package com.taiji.dianthus.service.sms.impl;

import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.dao.sms.SmsGroupUserRepository;
import com.taiji.dianthus.domain.sms.SmsGroupUser;
import com.taiji.dianthus.service.sms.SmsGroupUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName SmsGroupUserServiceImnpl
 * @Description
 * @Author H.M
 * @Date 2020/7/15
 */
@Service
public class SmsGroupUserServiceImpl implements SmsGroupUserService {

    @Autowired
    private SmsGroupUserRepository repository;


    @Override
    public Integer countByGroupId(String id) {
        return repository.countByGroupId(id);
    }

  /*  @Override
    public BusinessMessage getAllUserByGroupId(Integer pageSize, Integer currentPage, String userName, String phone, String groupId) {
        BusinessMessage message = new BusinessMessage();
        try {
            Sort sort = new Sort(Sort.Direction.DESC, "createTime");
            //分页参数
            Pageable pageable = PageRequest.of(currentPage, pageSize, sort);
            Page<SmsGroupUser> smsGroupuUserPage;
            //创建查询参数
            Specification<SmsGroupUser> spec = (Root<SmsGroupUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                List<Predicate> pl = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(userName)) {
                    pl.add(cb.like(root.<String>get("userName"), "%" + userName + "%"));
                }
                if (!StringUtils.isEmpty(phone)) {
                    pl.add(cb.like(root.<String>get("phone"), phone + "%"));
                }
                //查询未删除的
                pl.add(cb.equal(root.<Integer>get("enableFlag"), 1));
                pl.add(cb.equal(root.<Integer>get("groupId"), groupId));
                return cb.and(pl.toArray(new Predicate[0]));
            };
            smsGroupuUserPage = repository.findAll(spec, pageable);
            message.setMsg("查询群组用户列表成功");
            message.setData(smsGroupuUserPage);
            message.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("查询群组用户列表失败");
        }
        return message;
    }*/

    @Override
    public BusinessMessage deleteGroupUserById(String id) {
        BusinessMessage message = new BusinessMessage();
        try {
            repository.updateFlag(id);
            message.setSuccess(true);
            message.setMsg("删除群组用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("删除群组用户信息失败,系统异常");
        }
        return message;
    }

    @Override
    public BusinessMessage deleteGroupUserByIdArrays(String[] ids) {
        BusinessMessage message = new BusinessMessage();
        try {
            List<String> list = Stream.of(ids).collect(Collectors.toList());
            repository.updateFlagArrays(list);
            message.setSuccess(true);
            message.setMsg("批量删除群组用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("批量删除群组用户信息失败,系统异常");
        }
        return message;
    }

    @Override
    public BusinessMessage save(List<SmsGroupUser> smsGroupUserList) {
        BusinessMessage message = new BusinessMessage();
        try {
            List<SmsGroupUser> preGroupUserList = repository.getAllUserListByGroupIdBooks(smsGroupUserList.get(0).getGroupId());
            //求差集
            List<SmsGroupUser> differenceSet = smsGroupUserList.stream().filter(t -> !preGroupUserList.contains(t)).collect(Collectors.toList());
            List<SmsGroupUser> differenceSet2 = preGroupUserList.stream().filter(t -> !smsGroupUserList.contains(t)).collect(Collectors.toList());
            //此处指的是将与l2重复的删除
            differenceSet.removeAll(differenceSet2);
            //此处指加上l2
            differenceSet.addAll(differenceSet2);
            for (int i = 0; i < differenceSet.size(); i++) {
                SmsGroupUser ug = differenceSet.get(i);
                //取差集中在旧ID中进行删除  更新enableFlag=0
                if (null != preGroupUserList && preGroupUserList.size() > 0 && null != ug && preGroupUserList.contains(ug)) {
                    repository.updateFlag(ug.getId());
                    //取差集中在新ID中进行存储
                } else if (null != ug && smsGroupUserList.contains(ug)) {
                    repository.save(ug);
                }
            }
            message.setSuccess(true);
            message.setMsg("保存群组用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("保存群组用户信息失败,系统异常");
        }
        return message;
    }

    @Override
    public List<SmsGroupUser> getAllUserListByGroupIdNotPage(String groupId) {
        return repository.getAllUserListByGroupIdNotPage(groupId);
    }


    @Override
    public BusinessMessage listAll(Integer currentPage, Integer pageSize, String groupId, String userName, String userPhone) {
        BusinessMessage message = new BusinessMessage();
        try {
            Sort sort = new Sort(Sort.Direction.ASC, "userName").and(new Sort(Sort.Direction.DESC, "createTime"));
            //分页参数
            Pageable pageable = PageRequest.of(currentPage, pageSize, sort);
            Page<SmsGroupUser> smsGroupUserPage;
            //创建查询参数
            Specification<SmsGroupUser> spec = (Root<SmsGroupUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                List<Predicate> pl = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(userName)) {
                    pl.add(cb.like(root.<String>get("userName"), "%" + userName + "%"));
                }
                if (!StringUtils.isEmpty(userPhone)) {
                    pl.add(cb.like(root.<String>get("userPhone"), userPhone + "%"));
                }
                //查询未删除的
                pl.add(cb.equal(root.<Integer>get("enableFlag"), 1));
                pl.add(cb.equal(root.<Integer>get("groupId"), groupId));
                return cb.and(pl.toArray(new Predicate[0]));
            };
            smsGroupUserPage = repository.findAll(spec, pageable);
            message.setMsg("查询群组用户列表成功");
            message.setData(smsGroupUserPage);
            message.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("查询群组用户列表失败");
        }
        return message;
    }

    @Override
    public BusinessMessage getCountUserByGroupId(String groupId) {
        BusinessMessage message = new BusinessMessage();
        try {
            List<SmsGroupUser> list = repository.getAllUserListByGroupIdNotPage(groupId);
            if (list != null && list.size() > 0) {
                message.setSuccess(true);
                message.setMsg("查询指定群组用户信息成功");
                message.setData(list.size());
            }

        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("查询指定群组用户信息失败,系统异常");
        }
        return message;
    }

    @Override
    public BusinessMessage saveOneGroupUser(SmsGroupUser groupUser) {
        BusinessMessage message = new BusinessMessage();
        try {
            repository.saveAndFlush(groupUser);
            message.setSuccess(true);
            message.setMsg("添加自定义群组用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("添加自定义群组用户信息失败");
        }
        return message;
    }

    @Override
    public BusinessMessage checkUserPhoneByGroup(String groupId, String userPhone) {
        BusinessMessage message = new BusinessMessage();
        List<SmsGroupUser> list = repository.checkUserPhoneByGroup(groupId, userPhone);
        if (list.size() > 0) {
            message.setSuccess(true);
        }
        return message;
    }

    @Override
    public List<SmsGroupUser> getAllUserListByGroupIdBooks(String groupId) {
        return repository.getAllUserListByGroupIdBooks(groupId);
    }


}
